import java.awt.BorderLayout;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Client extends Panel implements Runnable {
	private TextField tf = new TextField();
	private TextArea ta = new TextArea();
	private Socket socket;
	private DataOutputStream dout;
	private DataInputStream din;

	ActionListener al = new ActionListener() {
		public void actionPerformed(ActionEvent e) {
			FileChooser filechooser = new FileChooser();
			filechooser.run();
		}
	};
	
	public Client (String host, int port) {
		setLayout(new BorderLayout());
		JButton b = new JButton("Send File");
		b.setBounds(100, 50, 75, 35);
		b.addActionListener(al);
		add("South", b);
		add( "North", tf );
		add( "Center", ta );
		
		

		
		tf.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				processMessage ( e.getActionCommand());
			}
		});
		
		
			try {
				socket = new Socket(host, port);
				System.out.println("connection to "+socket);
				din= new DataInputStream(socket.getInputStream());
				dout = new DataOutputStream (socket.getOutputStream());
				new Thread(this).start();
			} 
			catch (IOException ie) {
				System.out.println(ie);}
			}
			
	private void processMessage (String message) {
				try {
					// Send it to the server
					dout.writeUTF(message);
					// Clear out text input field
					tf.setText( "" );
				} catch( IOException ie ) { System.out.println( ie ); }
		}
	
	public void run() {
				try {
					while (true){
						String message = din.readUTF();
						ta.append(message+"\n");
					}
				} catch( IOException ie ) { System.out.println( ie ); }
			}
	

	public static void main (String[] args){

			JFrame jframe = new JFrame();
			jframe.setSize(400, 400);
		    String host = args[0];
			//String host = "localhost";
			//int port = Integer.parseInt(args[1]);
			int port = 5000;
			jframe.add(new Client(host, port));
			jframe.setVisible(true);
		}
}
	



